import InputIcon from "@src/components/inputIcon";
import SearchIcon from "@src/assets/search.svg?react"
import Return2Icon from "@src/assets/return2.svg?react"
import {useNavigate} from "react-router-dom";
import "./index.scss"
import React, {useState} from "react";
import {debounce} from "@src/utils/method.ts"
import thinking2 from "@src/assets/thinking2.png"
import {getSearchSuggest} from "@src/services/music"
import {useRequest} from "ahooks";
//搜索提示页
export default function SearchSuggest() {
    const navigate = useNavigate();
    const [search, setSearch] = useState("");
    const searchSuggestApi = useRequest(getSearchSuggest, {manual: true})

    //获取搜索提示 + 防抖
    const searchSuggestApiRun = debounce((value: string) => {
        if (value.trim() != "") {
            searchSuggestApi.run(value)
        }
    }, 1000);

    function inputChange(e: React.ChangeEvent<HTMLInputElement>) {
        setSearch(e.target.value)
        searchSuggestApiRun(e.target.value)
    }

    return <div className="search-suggest">
        <div className="head centered">
            <Return2Icon onClick={() => navigate(-1)}></Return2Icon>
            <InputIcon type="search" Icon={<SearchIcon></SearchIcon>} placeholder="搜索你想找的歌" onChange={inputChange}
                       onKeyDown={(e) => {
                           if (e.key === 'Enter') {
                               if (search.trim() !== "") {
                                   navigate("/home/music/search", {state: search})
                               }
                           }
                       }}></InputIcon>
        </div>

        {(searchSuggestApi.data && searchSuggestApi.data.result.allMatch) ?
            <ul>
                {searchSuggestApi.data?.result?.allMatch.map((item) => (
                    <li key={item.keyword} onClick={() => navigate("/home/music/search", {state: item.keyword})}>
                        <SearchIcon/><span className="text-overflow-1">{item.keyword}</span>
                    </li>))}
            </ul> :
            <div className="centered">
                <img width="100%" src={thinking2} alt=""/>
            </div>}
    </div>
}